﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.Service.Data;
using System.Data.Common;
using System.Data;

namespace Sinacor.OMM.OrderExecutor.ResourceAccess
{
    public class BusinessExecutor : BaseResourceAccess
    {
        
        private Int32 _companyId;
        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="companyID"></param>
        public BusinessExecutor(Int32 companyId)
            : base(companyId)
        {
            _companyId = companyId;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Execute process order
        /// </summary>
        public int ExecuteProcessBusiness()
        {
            string sql = string.Empty;

            using (DbCommand command = this.DataBase.GetStoredProcCommand("PR_NEGOCIOS.NEGAUT380_Proxy"))
            {
                //
                this.DataBase.AddInParameter(command, "P_SCODCORR", DbType.String, RetrieveStockMarketId());
                this.DataBase.AddOutParameter(command, "R_NCTRLREC", DbType.Int32, 9);
                this.DataBase.AddOutParameter(command, "R_NREPROC", DbType.Int32, 20);
                
                //
                this.DataBase.ExecuteNonQuery(command);

                long i = Convert.ToInt64(this.DataBase.GetParameterValue(command, "R_nCtrlRec"));
                int i2 = Convert.ToInt32(this.DataBase.GetParameterValue(command, "R_nReproc"));
                return i2;
            }

        }

        public string RetrieveStockMarketId()
        {
            
            string sql;
            string strStockMarketId = string.Empty;
            sql = @"
                    SELECT CD_EMPR_BOLSA
                    FROM TGELOCAL B
                    WHERE B.CD_BOLSA='1'
                      AND B.CD_PRACA='1'
                      AND B.IN_MEMB_BOLSA='S'
                      AND B.IN_PRAC_PRINC='S'
                      AND CD_EMPRESA = TO_NUMBER(" + _companyId + ")";
            IDataReader reader = null;
            using (DbCommand command = this.DataBase.GetSqlStringCommand(sql))
            {
                reader = this.DataBase.ExecuteReader(command);
            }

            if (reader.Read())
            {
                strStockMarketId = reader.GetValue<string>("CD_EMPR_BOLSA");
            }
            reader.Close();
            reader.Dispose();
            reader = null;

            return strStockMarketId;
        }

        #endregion

    }
}
